package com.zhangx.mq.demo.rabbit.config;

import com.zhangx.mq.demo.rabbit.receiver.Receiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName RabbitMqConfig
 * @Description 配置类,自己组装。
 * @Author zhangx
 * @Date 2021/4/23 8:31
 **/
@Slf4j
@Configuration
public class RabbitMqConfig {

    @Value("${spring.rabbitmq.host}")
    private String address;

    @Value("${spring.rabbitmq.port}")
    private String port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(address + ":" + port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
//        todo 1 消息发送者确认模式
//        mq会在接收成功后有一个确认
        connectionFactory.setPublisherConfirms(true);
//        todo 2发送成功返回
        connectionFactory.setPublisherReturns(true);
        return connectionFactory;
    }

    @Bean
    public RabbitTemplate newRabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());

        //        todo 1 消息发送者确认模式-监听，发送成功不代表会被正确路由
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack){
                    log.info("发送给MQ成功");
                }else {
                    log.info("发送给MQ失败，原因：{}",cause);
                }
            }
        });

        //        todo 2 发给给MQ后，如果失败的通知，比如无法绑定到queue
//        强制委托，不开启强制委托ReturnCallback不生效
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("消息无法路由！！");
                log.info("replyCode={},replyText={}",replyCode,replyText);
                log.info("exchange={},routingKey={}",exchange,routingKey);
                log.info(new String(message.getBody()));
            }
        });


        return rabbitTemplate;
    }

    /**
     * 消费成功后手动确认
     * @param receiver
     * @return
     */
    @Bean
    public SimpleMessageListenerContainer messageListenerContainer(Receiver receiver){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
        container.setQueues(queue1());
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener(receiver);
        return container;
    }

    /**
     * 一个直接交换器
     * @return
     */
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("DirectExchange");
    }

    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange("TopicExchange");
    }

    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("FanoutExchange");
    }

    @Bean
    public Queue queue1(){
//        没设置持久化，spring 中默认就是
        return new Queue("queue1");
    }

    @Bean
    public Queue queue2(){
//        没设置持久化，spring 中默认就是
        return new Queue("queue2");
    }

    /**
     * 绑定关系
     * @return
     */
    @Bean
    public Binding bindingQueueDirect(){
        return BindingBuilder
                .bind(queue1())
                .to(directExchange())
                .with("red");
    }

    @Bean
    public Binding bindingQ2Fanout(){
        return BindingBuilder.bind(queue2()).to(fanoutExchange());
    }
    @Bean
    public Binding bindingQ1Tpoic(){
        return BindingBuilder.bind(queue1()).to(topicExchange()).with("red.*");
    }



}
